<template>
<div id="Sidebar">
  <!-- 退出账户确认框 -->
  <el-dialog
    title="提示"
    :visible.sync="quitAccountDialogVisible">
    <span>确认退出账户？</span>
    <span slot="footer" class="dialog-footer">
    <el-button @click="quitAccountDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="quitAccountOk" :loading="btnLoading">确 定</el-button>
  </span>
  </el-dialog>

  <!-- 修改密码操作框 -->
  <el-dialog
    title="密码修改"
    :visible.sync="modifyPwdVis">
    <el-form :model="modifyPwdForm" status-icon :rules="modifyPwdFormRules" ref="modifyPwdForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input
          :disabled="btnLoading"
          type="password" v-model="modifyPwdForm.oldPassword" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item
        label="新密码" prop="newPassword">
        <el-input
          :disabled="btnLoading"
          type="password" v-model="modifyPwdForm.newPassword" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="newPasswordRepeat">
        <el-input
          :disabled="btnLoading"
          type="password" v-model="modifyPwdForm.newPasswordRepeat" auto-complete="off"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="() => { resetForm('modifyPwdForm'); modifyPwdVis = false }">取 消</el-button>
      <el-button type="primary" @click="modifyPwdOk('modifyPwdForm')" :loading="btnLoading">确 定</el-button>
    </span>
  </el-dialog>

  <!-- 退出账户弹出框 -->
  <el-popover
    ref="quitAccount"
    placement="bottom-start"
    width="100"
    v-model="accountMenuPopVis">
    <div
      class="account_menu"
      @click="() => { accountMenuPopVis = false; modifyPwdVis = true }">
      修改密码
    </div>
    <div
      class="account_menu"
      @click="quitAccountDialogVisible = true">
      退出账户
    </div>
  </el-popover>

  <div class="sidebar_wrapper">
    <div class="left">
      <img width="74px" src="../../assets/image/logo.png" alt="" @click="returnIndex">
      <!--<h3>COMEI</h3>-->
    </div>
    <div class="right">
      <div class="user_block">
        <div class="portrait">
          <span @click="clickAvatar">
            <img width="60px" height="60px" :src="userInfo.avatar | handleAvatarSIze" alt="">
          </span>
        </div>
        <div class="name">
          <!-- 用户名 -->
          <h4 v-popover:quitAccount>{{userInfo.nickname}}</h4>
        </div>
      </div>
      <div class="function_btn_block">
        <ul>
          <slot v-for="(menu, idx) in menuData">
            <router-link
              v-if="menu.show && !menu.children"
              :key="`1-${menu.name}`"
              :to="{ name: menu.name }"
              tag="li"
            >
              <div class="menu_item_con">
                <span :class="menu.icon"></span>
                <span v-text="menu.text"></span>
              </div>
            </router-link>
            <li
              v-if="menu.show && menu.children"
              :key="`2-${menu.name}`">
              <div class="menu_item_con" @click="shiftChildShow(idx)" style="disply: block; width: 100%;">
                <span :class="menu.icon"></span>
                <span v-text="menu.text"></span>
                <span v-if="!menu.showChild" class="right_more_icon el-icon el-icon-arrow-right"></span>
                <span v-if="menu.showChild" class="right_more_icon el-icon el-icon-arrow-down"></span>
              </div>
              <ul v-if="menu.showChild" class="child_menu_block">
                <router-link
                  v-for="child in menu.children"
                  :key="child.name"
                  :to="{ name: child.name }"
                  tag="li"
                >
                  <!-- <span :class="child.icon"></span> -->
                  <div class="menu_child_con">
                    <span v-text="child.text"></span>
                  </div>
                </router-link>
              </ul>
            </li>
          </slot>
        </ul>
      </div>
    </div>
  </div>
</div>
</template>

<script>
import API from '@/config/api.js'
import ErrorConfig from '@/config/error.config.js'

export default {
  name: 'Sidebar',
  mounted () {
    this.$nextTick(() => this.init())
  },
  data () {
    const validateOldPwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入原密码'))
      }
      callback()
    }
    const validateNPwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else {
        if (this.modifyPwdForm.newPasswordRepeat !== '') {
          this.$refs.modifyPwdForm.validateField('newPasswordRepeat')
        }
        callback()
      }
    }
    const validateNPwd2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码'))
      } else if (value !== this.modifyPwdForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      isCollapse: true,
      accountMenuPopVis: false,
      userInfo: JSON.parse(window.sessionStorage.getItem('userInfo')),
      quitAccountDialogVisible: false,
      btnLoading: false,
      menuData: {
        home: {
          name: 'welcome', icon: 'iconfont comei-welcome', text: '首页', show: true
        },
        catelog: {
          name: 'classification', icon: 'iconfont comei-classification', text: '分类管理', show: false
        },
        banner: {
          name: 'banner', icon: 'iconfont comei-banner', text: 'Banner管理', show: false
        },
        commodity: {
          name: 'product', icon: 'iconfont comei-product', text: '商品管理', show: false
        },
        event: {
          name: 'activity', icon: 'iconfont comei-activity', text: '活动管理', show: false
        },
        order: {
          name: 'order', icon: 'iconfont comei-order', text: '订单管理', show: false
        },
        withdraw: {
          name: 'withdraw', icon: 'iconfont comei-withdraw', text: '提现管理', show: false
        },
        ticket: {
          name: 'ticket', icon: 'iconfont comei-ticket', text: '奖券管理', show: false
        },
        passport: {
          name: 'user', icon: 'iconfont comei-user', text: '用户管理', show: false
        },
        report: {
          name: 'report',
          icon: 'iconfont comei-report',
          text: '统计报表',
          show: false,
          showChild: false,
          children: [{ name: 'has_pay_report', icon: 'iconfont comei-report', text: '已付款订单' }]
        }
      },
      modifyPwdVis: false,
      modifyPwdFormRules: {
        oldPassword: [
          { validator: validateOldPwd, trigger: 'blur' }
        ],
        newPassword: [
          { validator: validateNPwd, trigger: 'blur' }
        ],
        newPasswordRepeat: [
          { validator: validateNPwd2, trigger: 'blur' }
        ]
      },
      modifyPwdForm: {
        oldPassword: '',
        newPassword: '',
        newPasswordRepeat: ''
      }
    }
  },
  filters: {
    handleAvatarSIze: (value) => {
      return `${value}&imageView2/1/w/60/h/60`
    }
  },
  methods: {
    async init () {
      const response = await API.getMenuList()
      const { code, data } = response
      if (code === 1) {
        data.forEach(item => {
          if (this.menuData[item.id]) {
            this.menuData[item.id].show = true
          }
        })
      } else {
        if (code === -1) {
          const { msg } = response
          this.$message.error(msg)
        } else {
          this.$message.error(ErrorConfig[code])
        }
      }
    },
    async quitAccountOk () { // 退出
      this.btnLoading = true
      const response = await API.loginOut()
      this.btnLoading = false
      const { code } = response
      if (response.code === 1) {
        window.sessionStorage.setItem('userInfo', null)
        this.$router.push({ path: '/login' })
      } else {
        if (code === -1) {
          const { msg } = response
          this.$message.error(msg)
        } else {
          this.$message.error(ErrorConfig[code])
        }
      }
    },
    returnIndex () {
      this.$router.push({ path: '/index' })
    },
    clickAvatar () {
      const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo'))
      this.$router.push({ name: 'user_detail', params: { id: userInfo.accountId } })
    },
    shiftChildShow (idx) { // 切换子菜单显示状态
      this.menuData[idx].showChild = !(this.menuData[idx].showChild)
    },
    resetForm (formName) { // 重置表单
      this.$refs[formName].resetFields()
    },
    modifyPwdOk (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.btnLoading = true
          const response = await API.modifyPwd(this.modifyPwdForm)
          this.btnLoading = false
          const { code } = response
          if (code === 1) { // succ
            this.modifyPwdVis = false
            this.$message({
              type: 'success',
              message: '修改成功'
            })
          } else { // err
            if (code === -1) {
              const { msg } = response
              this.$message.error(msg)
            } else {
              this.$message.error(ErrorConfig[code])
            }
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .clearfix {
    display: block;
    &:after {
      display: block;
      content: ".";
      height: 0;
      line-height: 0;
      clear: both;
      visibility: hidden;
    }
  }
  .account_menu {
    height: 50px;
    line-height: 50px;
    &:hover {
      cursor: pointer;
      color: brown;
    }
  }
  .sidebar_wrapper {
    /*display: -webkit-flex; !* Safari *!*/
    /*display: flex;*/
    @extend .clearfix;
    width: 330px;
    height: 100%;
    .left {
      float: left;
      width: 80px;
      height: 100%;
      text-align: center;
      background: #3b3a42;
      /*h3 {*/
        /*color: #fff;*/
        /*text-align: center;*/
      /*}*/
      img {
        cursor: pointer;
      }
    }
    .right {
      /*flex: 1;*/
      float: left;
      @extend .clearfix;
      width: 250px;
      box-shadow: 1px 0px 0px rgba(240,240,240,1);
      .user_block {
        position: relative;
        height: 80px;
        border-bottom: 1px solid #f0f0f0;
        .portrait {
          padding: 10px;
          span {
            cursor: pointer;
            display: inline-block;
            width: 60px;
            height: 60px;
            img {
              border-radius: 50%;
            }
          }
        }
        .name {
          position: absolute;
          top: 50%; left: 100px;
          transform: translateY(-50%);
          h4 {
            margin: 0;
            color: #5c5c5c;
            &:hover {
              cursor: pointer;
              color: darkgoldenrod;
            }
          }
        }
      }
      .function_btn_block {
        ul {
          margin: 0;
          padding: 0;
          list-style: none;
          li {
            list-style-type: none;
            .menu_item_con {
              position: relative;
              box-sizing: border-box;
              padding: 20px;
              .right_more_icon {
                position: absolute;
                top: 50%;
                right: 20px;
                transform: translateY(-50%)
              }
            }
            span {
              font-size: 14px;
              line-height: 14px;
              &.iconfont {
                display: inline-block;
                margin-right: 10px;
              }
            }
            &.router-link-active {
              color: #019ffe;
              background: #f5f5f5;
            }
            &:hover {
              color: #019ffe;
              cursor: pointer;
              background: #f5f5f5;
            }
            .child_menu_block {
              color: #000;
              font-size: 14px;
              line-height: 14px;
              .menu_child_con {
                padding: 20px 20px 20px 48px;
              }
            }
          }
        }
      }
    }
  }
</style>
